import router from "./router";
import store from "./store";
import { Message } from "element-ui";
import NProgress from "nprogress"; // progress bar
import "nprogress/nprogress.css"; // progress bar style
import { getToken } from "@/utils/auth"; // get token from cookie
import getPageTitle from "@/utils/get-page-title";

NProgress.configure({ showSpinner: false }); // 关闭进度条加载圈

// 白名单
const whiteList = ["/login", "/userLogisticsInformation"]; // no redirect whitelist

router.beforeEach(async(to, from, next) => {
  // 切换路由时取消上一个请求
  store.dispatch("request/removeHttpRequestList");

  // 启动进度条
  NProgress.start();

  // 设置页面标题
  document.title = getPageTitle(to.meta.title);

  // 确定用户是否已登录
  const hasToken = getToken();

  // 登录页面放行
  if (to.path === "/login") {
    next();
    // 完成进度条
    NProgress.done();
  }
  if (hasToken) { // 判断是否有token
    //  确定用户是否已通过getInfo获得其权限角色
    const hasRoles = store.getters.roles && store.getters.roles.length > 0;

    if (hasRoles) {
      if (localStorage.getItem("targetPath")) {
        const targetPath = localStorage.getItem("targetPath");
        localStorage.removeItem("targetPath");
        next({
          path: targetPath
        });
      } else {
        next();
      }

      // 完成进度条
      NProgress.done();
    } else {
      try {
        // 获取用户信息
        // 注意：权限码必须是对象数组！例如：['admin']或，['developer'，'editor']
        const data = await store.dispatch("user/getInfo");
        // 基于权限码生成可访问的路由
        const accessRoutes = await store.dispatch("permission/generateRoutes", data);
        // 动态添加可访问路由
        for (const item of accessRoutes) {
          router.addRoute(item);
        }

        // 设置replace:true，这样导航将不会留下历史记录
        next({ ...to, replace: true });

        // 完成进度条
        NProgress.done();
      } catch (error) {
        // 删除令牌并转到登录页面重新登录
        await store.dispatch("user/resetToken");

        Message.error(error || "Has Erorr");

        next(`/login?redirect=${to.path}`);

        // 完成进度条
        NProgress.done();
      }
    }
  } else {
    /* has no token*/

    if (whiteList.indexOf(to.path) !== -1) {
      // 在免登录白名单中，直接进入
      next();
    } else {
      // 没有访问权限的其他页面将重定向到登录页面。
      next(`/login?redirect=${to.path}`);
      NProgress.done();
    }
  }
});

router.afterEach((to) => {
  const tabsOption = store.getters["tabsOption"];
  // 判断当前路由中是否已经入栈
  const flag = tabsOption.findIndex((tab) => tab.route === to.path) > -1;
  if (!flag && !to.meta.hidden) {
    store.dispatch("tabs/addTab", {
      route: to.path,
      title: to.meta.title,
      name: to.name
    });
  }
  store.commit("tabs/SET_TAB", to.path);
  // finish progress bar
  NProgress.done();
});

// 在导航期间每次发生未捕获的错误时都会调用该处理程序
router.onError((error) => {
  console.error(error);

  const pattern = /Loading chunk (.*)+ failed/g;
  const isChunkLoadFailed = error.message.match(pattern);

  const targetPath = router.history.pending.fullPath;

  if (isChunkLoadFailed) {
    localStorage.setItem("targetPath", targetPath);
    window.location.reload();
  } else {
    console.log(error, "路由ERROR");
  }
});

